package org.shj.netty.chartper5;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter{
	
	private int counter;

	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
		String body = (String)msg;		
		System.out.println("This is " + (++counter) + " times receiv client: " + body);
		
		//(1) DelimiterBasedFrameDecoder
		body = "Server return:" + body + "$_";				
		ByteBuf resp = Unpooled.copiedBuffer(body.getBytes());
		ctx.writeAndFlush(resp);
	}
	
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
		ctx.flush();
	}
	
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		ctx.close();
	}
}
